<?php
header("Content-type: text/html; charset=utf-8");

require_once('json.inc.php');

$page = $_GET['page']; // get the requested page 
$limit = $_GET['rows']; // get how many rows we want to have into the grid 
$sidx = $_GET['sidx']; // get index row - i.e. user click to sort 
$sord = $_GET['sord']; // get the direction 
$event = intval($_GET['eve']);

if ($event == -1)
	return;

require('../dbconnect.inc.php');

$rs = $dbh->query('select count(*) as count from event_items where e_id=' . $event);

if ($rec = $rs->fetchAll(PDO::FETCH_COLUMN, 0))
{
	$count = $rec[0];
}
else
{
	$count = 0;
}

if( $count > 0 ) 
{ 
	$total_pages = ceil($count/$limit); 
} 
else 
{ 
	$total_pages = 0; 
} 

if ($page > $total_pages) 
	$page=$total_pages; 

$start = $limit * $page - $limit; // do not put $limit*($page - 1) 

if ($start < 0) 
	$start = 0;



$sth = $dbh->prepare(
'('.
'	SELECT ei.*, gp.name as sel_param_name '.
'		FROM event_items ei, groups gp '.
'		WHERE ei.sel_type = 0 AND gp.g_id = ei.sel_param AND ei.e_id = ' . $event .
') '.
'UNION '.
'('.
'	SELECT ei.*, CONCAT("Контроллер ",nm.c_id) as sel_param_name '.
'		FROM event_items ei, network_map nm '.
'		WHERE ei.sel_type = 1 AND nm.c_id = ei.sel_param AND ei.e_id = '. $event .
')  order by ' . $sidx . ' ' . $sord  .' limit :start,:limit');

$sth->bindParam(':start', intval($start), PDO::PARAM_INT);
$sth->bindParam(':limit', intval($limit), PDO::PARAM_INT);

$rs = $sth->execute();

$responce->page = $page; 
$responce->total = $total_pages; 
$responce->records = $count; 

$alldb = $sth->fetchAll(PDO::FETCH_ASSOC); 

$i = 0;

foreach( $alldb as $key => $val)
{
	$responce->rows[$key]['id'] = $i++;
	$responce->rows[$key]['cell'] = array($val['sel_type'], $val['sel_param'], $val['sel_param_name'] ,$val['act_type'], $val['act_param']);
}

echo json_encode($responce);

?>
